import {Component, EventEmitter, OnInit, Output} from '@angular/core';
import * as moment from 'moment';
import {NzMessageService} from "ng-zorro-antd/message";
import {NzModalService} from "ng-zorro-antd/modal";
import {CartService} from "../cart.service";
import {ConfigService} from "../../../../shared/services/config.service";
import {CustomerService} from "../../../../shared/services/product/customer.service";
import {SellService} from "../../../../shared/services/product/sell.service";

@Component({
    selector: 'app-cart',
    templateUrl: './cart.component.html',
    styleUrls: ['./cart.component.scss']
})
export class CartComponent implements OnInit {

    @Output() onSave = new EventEmitter();

    visible: boolean = false;
    paid: boolean = false;

    customer: any;
    customers: any = [];

    constructor(public cartService: CartService, public configService: ConfigService, private customerService: CustomerService, private sellService: SellService, private message: NzMessageService) {
    }

    ngOnInit(): void {
        this.customerService.getAll()
            .subscribe(res => {
                this.customers = res;
            });
    }


    /////////////////以下界面交互/////////////////////
    show() {
        this.visible = true;
    }

    submit() {
        if (!this.cartService.check()) {
            this.message.create("error", "库存不足！");
            return;
        }
        const sells = this.cartService.commit(this.customer);
        sells.forEach(sell => {
           sell.paid = this.paid;
        });
        this.sellService.createMany(sells).subscribe(res => {
            if (res.result) {
                this.cartService.out();
                this.visible = false;
                this.message.create("success", "提交成功！");
                sells.forEach(sell => {
                    const item = res.docs.find(item => item._id == sell._id);
                    if (item) {
                        sell.date = item.date;
                        sell.code = item.code;
                    }
                });
                //this.sellService.print(sells);
            }
        });
    }

    close() {
        this.visible = false;
    }

    compareObject(g1: any, g2: any): boolean {
        return g1 && g2 ? g1._id === g2._id : g1 === g2;
    }

}
